package com.gui.serialization;

import cn.hutool.core.util.IdUtil;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class KryoDemo {

    private static final String FILE_PATH = "D:\\code\\java\\java17_project\\java-base\\src\\main\\resources\\serial.bin";

    public static void main(String[] args) {

        Kryo kryo = new Kryo();
        kryo.register(SerialCatalog.class);
        kryo.register(HashMap.class);
        kryo.register(Date.class);
        // serial(kryo);
        deSerial(kryo);


    }

    private static void serial (Kryo kryo) {
        SerialCatalog catalog = createCatalog();

        try (
                FileOutputStream outputStream =
                        new FileOutputStream(FILE_PATH);
                Output output = new Output(outputStream)){
            kryo.writeObject(output, catalog);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void deSerial (Kryo kryo) {
        try (
                FileInputStream inputStream =
                        new FileInputStream(FILE_PATH);
                Input input = new Input(inputStream)){
            SerialCatalog catalog = kryo.readObject(input, SerialCatalog.class);
            System.out.println(catalog);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static SerialCatalog createCatalog(){
        SerialCatalog catalog = new SerialCatalog();
        catalog.setId(IdUtil.randomUUID());
        catalog.setAge(25);
        catalog.setName("zhangSan");
        Calendar calendar = Calendar.getInstance();
        calendar.set(2024, Calendar.JANUARY, 15);
        catalog.setCreateTime(calendar.getTime());
        Map<String, Object> attributeMap = new HashMap<>();
        attributeMap.put("email", "000000@163.com");
        catalog.setAttribute(attributeMap);
        return catalog;
    }
}
